<?php
namespace Modules\Admin\Http\Controllers\Admin\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Modules\Admin\Entities\Admin;

use Validator;
use ThrowException;
use Auth;

class AdminController extends Controller
{
    public function index(Request $req)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $options = $req->all();

        $options['where']['is_hidden'] = 0;

        $options['only'] = [
            'id',
            'uuid',
            'name',
            'phone',
            'roles' => [
                '*' => [
                    'id',
                    'uuid',
                    'name',
                ]
            ],
            'last_active_at',
            'created_at'
        ];

        $options['with'] = ['roles'];

        $list = Admin::getList($options);

        return $list->generateListResponse();
    }

    public function store(Request $req)
    {
        $rule = [
            'roles' => ['array']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $info = $req->all();

        $info = [
            'name' => $req->name,
            'phone' => $req->phone,
            'password' => $req->password,
        ];

        $item = Admin::create($info);

        $item->syncRoles($req->roles);

        return [
            'id' => $item->id,
            'uuid' => $item->uuid
        ];
    }

    public function update(Request $req, $uuid)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $item = Admin::getEntity([
            'uuid' => $uuid
        ]);

        if ($req->type === 'update') {
            $info = $req->input('attributes');
            unset($info['roles']);
            $item->update($info);
            $item->syncRoles($req->input('attributes.roles'));
        }
        elseif ($req->type === 'reset_password') {
            if (!$req->input('password') || strlen($req->password) < 6) {
                ThrowException::Conflict('管理员密码需要6位长度以上');
            }
            $item->update([
                'password' => md5($req->password)
            ]);
        }
    
        return [];
    }

    public function destroy(Request $req, $uuid)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $item = Admin::getEntity([
            'uuid' => $uuid
        ]);

        $item->delete();

        return [];
    }
}
